The following RegEx extract the hour from time strings like HH:mm, HH, or H.
For example, 9, 23, or 09:30.
ββββββββββββββ
Explanation:
β’ \b: Word boundary to ensure we capture only complete numbers, not parts of larger numbers.
β’ (?:...): Non-capturing group to match the following alternatives without creating a capture group.
β’ [01]?\d: Matches hours from 0 to 19. The ? allows for the hour to have one or two digits.
β’ 2[0-3]: Matches hours from 20 to 23.
β’ (?=:|$): Lookahead to ensure the hour is followed by a colon : (like in HH:mm) or the end of the string (like in H or HH).